/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servelt;

import DatabaseAccessing.Customer;
import DatabaseAccessing.CustomerTransaction;
import DatabaseAccessing.ProductModelController;
import DatabaseAccessing.Products;
import DatabaseAccessing.CustomerTransaction;
import DatabaseAccessing.TransactionModelController;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.type.CustomCollectionType;

/**
 *
 * @author MaramZahran
 */
public class AddToCart extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int productID = Integer.parseInt(request.getParameter("ProductID"));
        ProductModelController pMC = new ProductModelController();


        TransactionModelController tMC = new TransactionModelController();

        Products p = pMC.viewProductByID(productID);
        
            HttpSession session = request.getSession(false);
            if (session != null)
            {
                //int userID = (Integer) session.getAttribute("LOGIN_USER");
                Object userObj = session.getAttribute("LOGIN_USER");
                if(userObj!=null)
                {

                    Customer user = (Customer) userObj;

                 int userID = user.getCustomerId();
                 System.out.println("User ID  = "+userID);
                if (p.getAmount() != 0) {
                    List oldTransList = tMC.getUndoneTransactionsForSpecificProduct(userID, productID);

                    if ((oldTransList != null) && (oldTransList.size() != 0)) {
                        System.out.println("isnide  add to cart in if ");
                        
                        CustomerTransaction oldTran = (CustomerTransaction) oldTransList.get(0);
                        
                        int count = oldTran.getCount();
                        
                        count++;
                        
                        oldTran.setCount(count);
                        tMC.updateTransaction(oldTran);
                        
                    } else {
                        System.out.println("isnide  add to cart in else ");
                        
                        CustomerTransaction tranObject = new CustomerTransaction();
                        tranObject.setProductId(productID);
                        tranObject.setDone(false);
                        tranObject.setDate(new Date());
                        tranObject.setUnitPrice(p.getPrice());
                        tranObject.setCustomerId(userID);
                        tranObject.setCount(1);
                        tMC.addTransaction(tranObject);
                    }
                    int amount = p.getAmount();
                    amount--;
                    p.setAmount(amount);
                    pMC.editProduct(p);
                    List<CustomerTransaction> userCart = tMC.getUndoneTransactions(userID);
                    session.setAttribute("allproductinCarts", userCart);
                    Object catObj = session.getAttribute("category");
                    if(catObj!=null)
                    {
                        String cat = catObj.toString();
                        response.sendRedirect("search?category="+cat);
                    }
                    else
                    {
                        response.sendRedirect("Products.jsp");
                    }



                }
                }
            else
            {
                    out.println("Please sign in ");
                    Object cartObj = session.getAttribute("Cart");
                if (cartObj != null) {
                    boolean found = false;
                    List<CustomerTransaction> cart = (List) cartObj;

                    for (int i = 0; i < cart.size(); i++) {
                        System.out.println("!!!!!!!!!!!! cart size inside the for"+cart.size());
                        CustomerTransaction obj = (CustomerTransaction) cart.get(i);
                        if (obj.getProductId() == productID) {
                            int count = obj.getCount();
                            count++;
                            obj.setCount(count);
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        System.out.println("found");
                        CustomerTransaction tranObject = new CustomerTransaction();
                        tranObject.setProductId(productID);
                        tranObject.setDone(false);
                        tranObject.setDate(new Date());
                        tranObject.setUnitPrice(p.getPrice());
                        tranObject.setCustomerId(-1);
                        tranObject.setCount(1);
                        cart.add(tranObject);
                    }
                       /* int amount = p.getAmount();
                        amount--;
                        p.setAmount(amount);
                        pMC.editProduct(p);*/
                        session.setAttribute("Cart",cart);
                        System.out.println("set cart");
                        Object catObj = session.getAttribute("category");
                    if(catObj!=null)
                    {
                        String cat = catObj.toString();
                        response.sendRedirect("search?category="+cat);
                    }
                    else
                    {
                        response.sendRedirect("Products.jsp");
                    }

                    

                } else {
                     List<CustomerTransaction> cart = Collections.EMPTY_LIST;
                    Vector <CustomerTransaction> cartVector = new Vector<CustomerTransaction>();

                    CustomerTransaction tranObject = new CustomerTransaction();
                    tranObject.setProductId(productID);
                    tranObject.setDone(false);
                    tranObject.setDate(new Date());
                    tranObject.setUnitPrice(p.getPrice());
                    tranObject.setCustomerId(-1);
                    tranObject.setCount(1);
                    cartVector.add(tranObject);

                   /* int amount = p.getAmount();
                    amount--;
                    p.setAmount(amount);
                    pMC.editProduct(p);*/
                    cart = (List) cartVector;
                    session.setAttribute("Cart", cart);
                     Object catObj = session.getAttribute("category");
                    if(catObj!=null)
                    {
                        String cat = catObj.toString();
                        response.sendRedirect("search?category="+cat);
                    }
                    else
                    {
                        response.sendRedirect("Products.jsp");
                    }

                }


            }

            } else {
                Object cartObj = session.getAttribute("Cart");
                if (cartObj != null) {
                    boolean found = false;
                    List<CustomerTransaction> cart = (List) cartObj;

                    for (int i = 0; i < cart.size(); i++) {
                        CustomerTransaction obj = (CustomerTransaction) cart.get(i);
                        if (obj.getProductId() == productID) {
                            int count = obj.getCount();
                            count++;
                            obj.setCount(count);
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        CustomerTransaction tranObject = new CustomerTransaction();
                        tranObject.setProductId(productID);
                        tranObject.setDone(false);
                        tranObject.setDate(new Date());
                        tranObject.setUnitPrice(p.getPrice());
                        tranObject.setCustomerId(-1);
                        tranObject.setCount(1);
                        cart.add(tranObject);
                    }
                        int amount = p.getAmount();
                        amount--;
                        p.setAmount(amount);
                        pMC.editProduct(p);
                        session.setAttribute("Cart",cart);
                         Object catObj = session.getAttribute("category");
                    if(catObj!=null)
                    {
                        String cat = catObj.toString();
                        response.sendRedirect("search?category="+cat);
                    }
                    else
                    {
                        response.sendRedirect("Products.jsp");
                    }

                    

                } else {
                    List<CustomerTransaction> cart = Collections.EMPTY_LIST;
                    Vector <CustomerTransaction> cartVector = new Vector<CustomerTransaction>();

                    CustomerTransaction tranObject = new CustomerTransaction();
                    tranObject.setProductId(productID);
                    tranObject.setDone(false);
                    tranObject.setDate(new Date());
                    tranObject.setUnitPrice(p.getPrice());
                    tranObject.setCustomerId(-1);
                    tranObject.setCount(1);
                    cartVector.add(tranObject);
                    int amount = p.getAmount();
                    amount--;
                    p.setAmount(amount);
                    pMC.editProduct(p);
                    cart = (List) cartVector;
                    session.setAttribute("Cart", cart);
                     Object catObj = session.getAttribute("category");
                    if(catObj!=null)
                    {
                        String cat = catObj.toString();
                        response.sendRedirect("search?category="+cat);
                    }
                    else
                    {
                        response.sendRedirect("Products.jsp");
                    }

                }


            }

            // TODO output your page here
            /*out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet AddToCart</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet AddToCart at " + request.getContextPath() + "</h1>");
            out.println("Done");
            out.println("</body>");
            out.println("</html>");*/

        
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";

    }// </editor-fold>
}
